package com.kenliang.netty.rpc.core;

import com.kenliang.netty.rpc.config.RpcSystemConfig;
import com.kenliang.netty.rpc.model.MessageRequest;
import com.kenliang.netty.rpc.model.MessageResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author KenLiang
 * @description:
 * @date Created in 5:22 PM 2019/3/22.
 */
@Slf4j
public class MessageCallBack {

    private MessageRequest messageRequest;
    private MessageResponse messageResponse;

    private final ReentrantLock lock = new ReentrantLock(false);
    private final Condition finish = lock.newCondition();

    public MessageCallBack(MessageRequest messageRequest) {
        this.messageRequest = messageRequest;
    }


    //回调等待开始
    public MessageResponse start() {
        try {
            lock.lock();
            boolean timeout = finish.await(RpcSystemConfig.CLIENT_MESSAGE_CALLBACK_TIMEOUT, TimeUnit.MILLISECONDS);
            if (!timeout) {
                return this.messageResponse;
            }else{
                log.error("请求超时，MessageRequest :{}", messageRequest);
            }
        } catch (InterruptedException e) {
            log.error("MessageCallBack start():", ExceptionUtils.getStackTrace(e));
        } finally {
            lock.unlock();
        }
        return null;

    }

    //回调已等待到response
    public void over(MessageResponse messageResponse) {
        try {
            lock.lock();
            this.messageResponse = messageResponse;
            finish.signal();
        } finally {
            lock.unlock();
        }
    }
}
